// videoStorage.js
class VideoStorage {
  constructor() {
    this.dbName = "VideoDatabase";
    this.storeName = "videos";
    this.dbVersion = 1;
    this.db = null;
  }

  async initDB() {
    if (this.db) return this.db;

    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.dbVersion);

      request.onerror = (event) => {
        reject(`数据库打开失败: ${event.target.error}`);
      };

      request.onsuccess = (event) => {
        this.db = event.target.result;
        resolve(this.db);
      };

      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains(this.storeName)) {
          db.createObjectStore(this.storeName, { keyPath: "id" });
        }
      };
    });
  }

  async saveVideo(file) {
    const db = await this.initDB();

    // 先读取文件内容
    const fileData = await new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => resolve(e.target.result);
      reader.onerror = () => reject(reader.error);
      reader.readAsArrayBuffer(file);
    });

    return new Promise((resolve, reject) => {
      const transaction = db.transaction(this.storeName, "readwrite");
      const store = transaction.objectStore(this.storeName);

      // 创建清除请求 - 这是修复的关键点！
      const clearRequest = store.clear();

      clearRequest.onsuccess = () => {
        const videoData = {
          id: "current-video",
          name: file.name,
          type: file.type,
          size: file.size,
          data: fileData,
          timestamp: Date.now(),
        };

        // 添加新数据
        const addRequest = store.add(videoData);
        addRequest.onsuccess = () => resolve("视频存储成功");
        addRequest.onerror = (e) => reject(`添加失败: ${e.target.error}`);
      };

      clearRequest.onerror = (e) => reject(`清除失败: ${e.target.error}`);

      transaction.onerror = (e) => reject(`事务错误: ${e.target.error}`);
    });
  }

  async getVideoUrl() {
    const db = await this.initDB();

    return new Promise((resolve, reject) => {
      const transaction = db.transaction(this.storeName, "readonly");
      const store = transaction.objectStore(this.storeName);
      const request = store.get("current-video");

      request.onsuccess = () => {
        const videoData = request.result;
        if (!videoData) {
          reject("未找到存储的视频");
          return;
        }

        const blob = new Blob([videoData.data], { type: videoData.type });
        resolve(URL.createObjectURL(blob));
      };

      request.onerror = (e) => reject(`获取失败: ${e.target.error}`);
    });
  }
}

// 创建单例实例
const videoStorage = new VideoStorage();
export default videoStorage;
